var app = getApp()

const RongIMLib = app.globalData.RongIMLib;
const RongIMEmoji = app.globalData.RongIMEmoji;

const utils = require("../../utils/utils.js")

var params = {}; 

Page({

    /**
     * 页面的初始数据
     */
    data: {
        data: [], // 消息数据列表

        conversationList: [], // 会话列表

        messageTitleList: [{
                name: "系统消息",
                type: 0
            },
            {
                name: "聊天消息",
                type: 1
            },
        ],
        selected: 0,

        page:1,              // 页码

        loading: false,      // 加载中
        noData: false,       // 没有数据
        noMore: false,       // 没有更多
        hint: false,         // 是否提示
    },
    // 切换 tabbar
    changeTabbar(e) {
        var self = this;
        var type = e.target.dataset.type;
        this.setData({
            selected: type
        });

        if (type == 0) {
            this.getSystemMeg();
        }
    },
    // 获取系统消息
    getSystemMeg() {
        var self = this;
        var url = "/mytask/mymessage"
        wx.getStorage({
            key: 'user',
            success: function(res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                    },
                    success: function(res) {
                        var list = res.data;
                        if (list.code == 1 && list.data.data.length) {
                            self.setData({
                                data: list.data.data
                            })
                        } else {
                            wx.showToast({
                                image: "../../img/warning.png",
                                title: '暂无系统消息',
                            })
                        }
                    }
                })
            }
        })
    },
    // 处理会话列表
    handleList() {
        var self = this;
        var list = [];
        var arr = [];
        var conversationList = self.data.conversationList;
        conversationList.map((item, index) => {
			var user_id = item.targetId;
            if (item.conversationType == 1 && item.targetId != "undefined" ) {
                var targetId = 'char' + user_id;
                var conversation_user_data = "";
				item._sentTime = utils.getTime(item.sentTime);
				item._content = item.latestMessage.content.content;
				wx.getStorage({
					key: 'conversation_user_data',
					success: function(res) {
						conversation_user_data = res.data
						if (conversation_user_data[targetId]) {
							item.target = conversation_user_data[targetId]
							list.push(item)
							self.setData({
								conversationList: list
							})
						} else {
							self.userInfo(item, user_id, list, conversation_user_data)
						}
					},
					fail() {
						self.userInfo(item, user_id, list)
					}
				})
            }
        })
    },
    // 获取用户信息
    userInfo(conversation, user_id, lists, user_storage) {
        var self = this;

        var url = "/user/get_userinfo";
        user_storage = user_storage || {};
        var targetId = 'char' + user_id;
        wx.getStorage({
            key: 'user',
            success: function(res) {
                wx.request({
                    url: app.url.requestUrl + url,
                    method: 'POST',
                    data: {
                        openid: res.data.openid,
                        token: res.data.token,
                        user_id: user_id,
                    },
                    success: function(res) {
                        var list = res.data;
                        user_storage[targetId] = list.data[0];
                        if (list.code == 1) {
                            wx.setStorage({
                                key: 'conversation_user_data',
                                data: user_storage,
                            })
                            conversation.target = list.data[0];
                            lists.push(conversation)
                            self.setData({
                                conversationList: lists
                            })
                        } else {
                            wx.showToast({
                                image: "../../img/warning.png",
                                title: '获取会话用户失败',
                            })
                        }
                    }
                })
            }
        })
    },
	// 前往聊天界面
	gotoChat(e) {
		var self = this;
		let { currentTarget: { dataset : { item } } } = e;
		let { count } = item;
		let { target : { user_id } } = item;
		let { target : { name} } = item;

		wx.navigateTo({
			url: `../my-chat/my-chat?user_id=${user_id}&name=${name}`
		});

        var conversationType = RongIMLib.ConversationType.PRIVATE;
        var targetId = user_id;
        this.handleList();
        RongIMLib.RongIMClient.getInstance().clearUnreadCount(conversationType, targetId, {
            onSuccess: function () {
                // 清除未读消息成功
            },
            onError: function (error) {
                // error => 清除未读消息数错误码
            }
        });
		
	},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function() {
        var self = this;
        var messageTitleList = this.data.messageTitleList;

        this.setData({
            selected: messageTitleList[0].type
        })
        this.getSystemMeg();

        RongIMLib.RongIMClient.getInstance().getConversationList({
            onSuccess: function(list) {
                self.setData({
                    conversationList: list
                })
                params.self = self;
                app.globalData.writeInContent = writeInContent;
                self.handleList()
                // list => 会话列表集合
            },
            onError: function(error) {
                // do something
            }
        }, null);
    },
    // 加载更多
    onReachBottom(){
        var page = ++this.data.page;
        var noMore = this.data.noMore;
        var loading = this.data.loading;
    },
    // 分享
    onShareAppMessage: function() {

    }
})

// 写入文本消息
var writeInContent = function (num, message) {
    params.self.handleList()
}